<template>
  <v-form-designer ref="frmDesign" @save-event="saveEvent" :field-list-api="state.fieldsApi" />
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useLocaleStore } from '@/store/modules/locale'
import { getForm, editFormJson } from '@/api/develop/form'
import { PATH_URL } from '@/config/axios'
import { getToken } from '@/utils'
import router from '@/router'

const localeStore = useLocaleStore()
const { currentRoute } = useRouter()
const { t } = useI18n()

defineOptions({
  name: 'FormDesign'
})

const frmDesign = ref(null)
const state = reactive({
  formData: { status: 0, fmId: '' },
  fromPath: '/Develop/FormManage',
  fieldsApi: {
    URL: '',
    nameKey: 'fieldName',
    labelKey: 'showName',
    headers: { token: '' }
  }
})

// 渲染页面
onMounted(() => {
  const curLang = localeStore.getCurrentLocale.lang
  if (curLang == 'en') {
    state.fieldsApi.labelKey = 'enName'
  } else if (curLang == 'zh_HK') {
    state.fieldsApi.labelKey = 'hkName'
  }
  const designer = frmDesign.value as any
  designer.changeLanguage(curLang)
  init(designer)
})

//保存按钮事件
const saveEvent = (json) => {
  const saveJson = { fmId: state.formData.fmId, formJson: json }
  if (state.formData.status == 1) {
    ElMessageBox.confirm(t('form.saveTip'), t('common.warning'), {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
      .then(() => {
        saveFormJson(saveJson)
      })
      .catch(() => {})
  } else {
    saveFormJson(saveJson)
  }
}

//保存设计的页面
const saveFormJson = async (formJson) => {
  const result = (await editFormJson(formJson)) as any
  if (result.success) {
    ElMessage.success(t('group.saveSuccess'))
  } else {
    ElMessage.error(t(result.message))
  }
}

//初始化页面
const init = async (designer) => {
  const id = currentRoute.value.query.id as string
  const fromPath = currentRoute.value.query.fromPath as string
  if (fromPath) {
    state.fromPath = fromPath
  }
  //修改
  if (!id) {
    ElMessage.warning(t('common.paramError'))
    router.back()
    return
  }
  const data = (await getForm(id)) as any
  state.formData = data.data
  let content = JSON.parse(data.data.content)
  if (state.formData.status == 1) {
    const temp = data.data.tempContent
    if (temp && '{}' != temp) {
      content = JSON.parse(temp)
    }
  }
  state.fieldsApi.URL = PATH_URL + 'form/entity/getFields?entId=' + data.data.entId
  state.fieldsApi.headers.token = getToken()
  const json = content?.formJson
  designer.setFormJson(json)
  designer.loadFieldListFromServer()
}
</script>

<style lang="less" scoped></style>
